import logging
import traceback
import aiomysql

from fastapi import APIRouter
from pydantic import BaseModel
from fastapi import HTTPException
from apps.utils.sql_conn import get_db_cursor

doctor = APIRouter()

class DepartmentQuery(BaseModel):
    department: str

@doctor.get("/doctor/query", response_description="查询所有医生科室及每日接诊数据")
async def query_all_doctors_info():
    try:
        async with get_db_cursor() as cursor:
            await cursor.execute(
                """
                SELECT doctor, office, onetime, onepeople, twotime, twopeople,
                       threetime, threepeople, fourtime, fourpeople,
                       fivetime, fivepeople, sixtime, sixpeople,
                       seventime, sevenpeople
                FROM doctor
                """
            )
            doctors_data = await cursor.fetchall()

            if not doctors_data:
                raise HTTPException(
                    status_code=404,
                    detail="未找到任何医生信息"
                )

            # 按医生姓名封装数据
            result = {}
            for doctor_data in doctors_data:
                if isinstance(doctor_data, dict):
                    doctor_name = doctor_data["doctor"]
                    office = doctor_data["office"]
                    time_fields = [
                        doctor_data["onetime"],
                        doctor_data["twotime"],
                        doctor_data["threetime"],
                        doctor_data["fourtime"],
                        doctor_data["fivetime"],
                        doctor_data["sixtime"],
                        doctor_data["seventime"]
                    ]
                    people_fields = [
                        doctor_data["onepeople"],
                        doctor_data["twopeople"],
                        doctor_data["threepeople"],
                        doctor_data["fourpeople"],
                        doctor_data["fivepeople"],
                        doctor_data["sixpeople"],
                        doctor_data["sevenpeople"]
                    ]
                else:
                    doctor_name = doctor_data[0]  # 医生姓名是第一列
                    office = doctor_data[1]       # 科室是第二列
                    time_fields = doctor_data[2::2]  # 时间从第三列开始，每隔一列
                    people_fields = doctor_data[3::2]  # 人数从第四列开始，每隔一列

                daily_data = []
                for time, people in zip(time_fields, people_fields):
                    daily_data.append({
                        "time": time,
                        "people": people
                    })

                # 按医生姓名分组
                result[doctor_name] = {
                    "office": office,
                    "daily_data": daily_data
                }

            return result

    except aiomysql.Error as e:
        raise HTTPException(
            status_code=500,
            detail=f"数据库查询失败：{e.args[1]}"
        )
    except Exception as e:
        logging.error(f"医生查询接口异常: {traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=f"服务器内部错误：{str(e)}"
        )


@doctor.post("/doctor/query_by_department", response_description="根据科室查询余量数据")
async def query_register_by_department(dept: DepartmentQuery):
    try:
        async with get_db_cursor() as cursor:
            await cursor.execute(
                """
                SELECT office, onepeople, twopeople, threepeople,
                       fourpeople, fivepeople, sixpeople, sevenpeople
                FROM register 
                WHERE office = %s
                """,
                (dept.department,)
            )
            register_data = await cursor.fetchone()

            if not register_data:
                raise HTTPException(
                    status_code=404,
                    detail=f"未找到科室[{dept.department}]的余量数据"
                )

            if isinstance(register_data, dict):
                department = register_data["office"]
                remaining_fields = [
                    {"onepeople": register_data["onepeople"]},
                    {"twopeople": register_data["twopeople"]},
                    {"threepeople": register_data["threepeople"]},
                    {"fourpeople": register_data["fourpeople"]},
                    {"fivepeople": register_data["fivepeople"]},
                    {"sixpeople": register_data["sixpeople"]},
                    {"sevenpeople": register_data["sevenpeople"]}
                ]
            else:
                department = register_data[0]
                remaining_fields = [
                    {"onepeople": register_data[1]},
                    {"twopeople": register_data[2]},
                    {"threepeople": register_data[3]},
                    {"fourpeople": register_data[4]},
                    {"fivepeople": register_data[5]},
                    {"sixpeople": register_data[6]},
                    {"sevenpeople": register_data[7]}
                ]

            return {
                "department": department,
                "remaining_data": remaining_fields
            }

    except aiomysql.Error as e:
        raise HTTPException(
            status_code=500,
            detail=f"数据库查询失败：{e.args[1]}（错误代码：{e.args[0]}）"
        )
    except Exception as e:
        logging.error(f"科室余量查询接口异常: {traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=f"服务器内部错误：{str(e)}"
        )
